package com.mjk.manager.task.work;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.model.BaseEntity;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.base.work.BaseWork;
import com.mjk.common.base.work.annotation.BeeWork;
import com.mjk.common.core.jdbc.annotation.ArcSharding;
import com.mjk.common.core.jdbc.service.parse.type.BeeParseType;
import com.mjk.common.core.jdbc.util.ShardingUtils;
import com.mjk.common.core.jdbc.util.provider.SqlProvider;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import com.mjk.common.util.BeanUtils;
import com.mjk.manager.task.dto.TaskDto;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * 获取表结构 用户codemirror 的表 字段提示功能
 * @author Administrator
 *
 */
@BeeWork(work = "sqltable")
public class SqlPraseTablesWork extends BaseWork implements BeeApplicationListener {
	private final Map<String,List<String>> TABLE_INFO = new HashMap<>();
	/**
	 * 获取表结构用于提取表字段
     */
	public BeeResponse getSqlTableHint(TaskDto dto) {
		return BeeError.BEE_SUC.tranceError(TABLE_INFO);
	}
	
	/**
	 * 获取SQL预览结果
	 */
	public BeeResponse parasSql(TaskDto dto) {
		Map<String,Object> sqlResult = BeeParseType.getParsing(BeeParseType.SQL).parsing(dto.getSql(), BeanUtils.beanToMap(dto));
		return BeeError.BEE_SUC.tranceError(sqlResult);
		
	}
	@Override
	public void doApplicationEvent(ContextRefreshedEvent event) {
		Map<String, BaseEntity> entitys =event.getApplicationContext().getBeansOfType(BaseEntity.class);
		for(Entry<String,BaseEntity> entry : entitys.entrySet()) {
            ArcSharding sharding = ShardingUtils.getArcSharding(entry.getValue());
            if (null != sharding) {
                continue;
            }
			TABLE_INFO.put(sharding.table(),
                    SqlProvider.getValidTableFiled(entry.getValue()).stream().map(Field::getName)
            .collect(Collectors.toList()));
		}
	}
}
